package com.tianhui.consignortwofei.mvp.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.fgs.common.CommonModel;
import com.fgs.common.CommonResponse;
import com.fgs.common.api.CommonConfig;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.dialog.OperateTipDialog;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.api.OrderApiService;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.contract.OrderListContract;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.OrderCondition;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderOperateInfo;
import com.tianhui.consignortwofei.mvp.presenter.OrderListPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.SaleCarFreightActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.SaleCarFreightLookActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.VehicleTrajectoryActivity;
import com.tianhui.consignortwofei.mvp.ui.adapter.XiaoWeiJiSuanListAdapter;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.pattern.orderOprate.IOrderOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.FreightOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.TerminateDispatchOperate;
import com.tianhui.consignortwofei.pattern.orderOprate.impl.VehicleTrajectoryOperate;
import com.tianhui.consignortwofei.pattern.orderStatus.status.IOrderStatus;
import com.tianhui.consignortwofei.widget.QRCodeDialog;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.enums.ThreadType;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xutil.app.IntentUtils;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.security.Base64Utils;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.inter.OnItemClickListener;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;

/**
 * @author fgs
 * @date 2020/8/27
 * @description
 **/
public class XiaoWeiJiSuanListFragment extends SearchFragment<OrderListContract.View, OrderListContract.Presenter> implements OrderListContract.View {

    private boolean isNeedLazyLoad = true;
    private IOrderStatus mIOrderStatus;
    private String mSearchKey;
    private int setWhichShow;

    public XiaoWeiJiSuanListFragment() {
        // Required empty public constructor
    }

    @Override
    public boolean isNeedLazyLoad() {
        return this.isNeedLazyLoad;
    }

    public static XiaoWeiJiSuanListFragment newInstance(IOrderStatus iOrderStatus) {
        XiaoWeiJiSuanListFragment orderListFragment = new XiaoWeiJiSuanListFragment();
        orderListFragment.setOrderStatus(iOrderStatus);
        return orderListFragment;
    }

    private XiaoWeiJiSuanListFragment setOrderStatus(IOrderStatus iOrderStatus) {
        mIOrderStatus = iOrderStatus;
        return this;
    }

    public XiaoWeiJiSuanListFragment setIsNeedLazyLoad(boolean isNeedLazyLoad) {
        this.isNeedLazyLoad = isNeedLazyLoad;
        return this;
    }

    public XiaoWeiJiSuanListFragment setSearchKey(String searchKey) {
        mSearchKey = searchKey;
        return this;
    }

    public XiaoWeiJiSuanListFragment setWhichShow(int num) {
        this.setWhichShow = num;
        return this;
    }


    @Override
    protected OrderListContract.View createView() {
        return this;
    }

    @Override
    protected OrderListContract.Presenter createPresenter() {
        return new OrderListPresenter(getContext());
    }


    @Override
    public RecyclerArrayAdapter createAdapter() {
        return new XiaoWeiJiSuanListAdapter(getContext(), mIOrderStatus,setWhichShow);
    }

    @Override
    protected void initListener() {

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (0==setWhichShow) {
                    Object object = mAdapter.getAllData().get(position);
                    if (object instanceof OrderInfo) {
                        OrderInfo orderInfo = (OrderInfo) object;
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                        bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());

                        //运费计算
                        yunfeiJIsuan(orderInfo);

//                    if (mIOrderStatus.getOrderStatusType() != OrderType.TYPE_PAYMENT) {
//                        openActivity(OrderDetailActivity.class, bundle);
//                    }
                    }
                }else if (1==setWhichShow){
                    Object object = mAdapter.getAllData().get(position);
                    if (object instanceof OrderInfo) {
                        OrderInfo orderInfo = (OrderInfo) object;
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
                        bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());

                        //运费计算只看
//                        yunfeiJIsuanLook(orderInfo);
                        openActivity(SaleCarFreightLookActivity.class, bundle);

//                    if (mIOrderStatus.getOrderStatusType() != OrderType.TYPE_PAYMENT) {
//                        openActivity(OrderDetailActivity.class, bundle);
//                    }
                    }

                }

            }
        });

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                Object object = mAdapter.getAllData().get(position);
                OrderInfo orderInfo = null;
                if (object instanceof OrderInfo) {
                    orderInfo = (OrderInfo) object;
                }
                Bundle bundle;
                OrderOperateInfo operateInfo;
                if (orderInfo != null) {
                    switch (view.getId()) {
                        case R.id.iv_phone:
                            if (!TextUtils.isEmpty(orderInfo.drivertel)) {
                                startActivity(IntentUtils.getDialIntent(orderInfo.drivertel));
                            } else {
                                ToastUtil.showShortToast("未识别到司机电话");
                            }

                            break;
                        case R.id.ll_driver_line_body:


                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "车辆轨迹";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.iOrderOperate = new VehicleTrajectoryOperate();
                            if (operateInfo.orderInfo != null) {
                                if (operateInfo.orderInfo.isstate == 7 || operateInfo.orderInfo.isstate == 9 || operateInfo.orderInfo.isstate > 11) {
                                    Intent intent = new Intent(getContext(), VehicleTrajectoryActivity.class);
                                    bundle = new Bundle();
                                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, operateInfo.orderInfo);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                } else {
                                    ToastUtil.showShortToast("该订单无车辆轨迹信息");
                                }
                            } else {
                                ToastUtil.showShortToast("获取订单信息失败");
                            }

                            break;


                        case R.id.tv_jisuan:
                            if (mIOrderStatus != null) {
                                //运费计算
                                yunfeiJIsuan(orderInfo);
                            }

                            break;
                        case R.id.tv_cancel:
                            operateInfo = new OrderOperateInfo();
                            operateInfo.operate = "终止单据";
                            operateInfo.orderInfo = orderInfo;
                            operateInfo.iOrderOperate = new TerminateDispatchOperate();
                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
                            break;
//                        case R.id.tv_cancel:
//
//
//                            operateInfo = new OrderOperateInfo();
//                            operateInfo.operate = "终止单据";
//                            operateInfo.orderInfo = orderInfo;
//                            operateInfo.iOrderOperate = new TerminateDispatchOperate();
//                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
//
//
//                            break;
//
//                        case R.id.tv_true_shou:
//
//                            operateInfo = new OrderOperateInfo();
//                            operateInfo.operate = "确认收货";
//                            operateInfo.orderInfo = orderInfo;
//                            operateInfo.isEnable = orderInfo.isrecelve == 0;
//                            operateInfo.iOrderOperate = new DeliveryConfirmOperate();
//                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
//
//                            break;
//                        case R.id.tv_true_zhuang:
//
//                            operateInfo = new OrderOperateInfo();
//                            operateInfo.operate = "确认装车";
//                            operateInfo.orderInfo = orderInfo;
//                            operateInfo.isEnable = orderInfo.istrans == 0;
//                            operateInfo.iOrderOperate = new LoadingConfirmOperate();
//                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
//                            break;
//                        case R.id.tv_change_price://调整价格
//                            showTerminateDialog(orderInfo);
//
//                            break;
//                        case R.id.tv_change_weight://调整重量
//                            showWeightDialog(orderInfo);
//
//                            break;
//                        case R.id.tv_change_hedan:
//
//                            operateInfo = new OrderOperateInfo();
//                            operateInfo.operate = "合单";
//                            operateInfo.orderInfo = orderInfo;
//                            operateInfo.isEnable = orderInfo.istrans == 0;
//                            operateInfo.iOrderOperate = new LoadingConfirmOperate();
////                            operateInfo.iOrderOperate.orderOperate(getContext(), operateInfo);
//
//                            bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, operateInfo.orderInfo);
//                            bundle.putInt(KeyValue.KEY_TYPE, OrderType.TYPE_HE_DAN);
//                            Intent intent = new Intent(getContext(), HeDanDetailActivity.class);
//                            intent.putExtras(bundle);
//                            getContext().startActivity(intent);
//                            break;


//                    case R.id.item_order_list_submitTextView:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, orderInfo);
//                            bundle.putInt(KeyValue.KEY_TYPE, mIOrderStatus.getOrderStatusType());
//                            openActivity(OrderDetailActivity.class, bundle);
//                        }
//
//                        break;
//                    case R.id.item_order_list_shareOrderCodeTextView:
//                        if (orderInfo != null) {
//                            showShareCode(orderInfo);
//                        }
//                        break;
//                    case R.id.item_order_list_editOrderTextView:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString(KeyValue.KEY_ID, orderInfo.id);
//                            openActivity(EditDeliveryGoodsStepOneActivity.class, bundle);
//                        }
//                        break;
//                    case R.id.tv_tonghua:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("sourcenum", orderInfo.billno);
//                            openActivity(TongHuaLogActivity.class, bundle);
//                        }
////                        Toast.makeText(getContext(), "通话记录", Toast.LENGTH_SHORT).show();
//                        break;
//                    case R.id.tv_liulan:
//                        if (orderInfo != null) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("sourcenum", orderInfo.billno);
//                            openActivity(LiuLanLogActivity.class, bundle);
//                        }
//                        Toast.makeText(getContext(), "浏览记录", Toast.LENGTH_SHORT).show();
//                        break;
                    }
                }else {
                    ToastUtil.showShortToast("数据获取错误");
                }
            }
        });

    }

    private void showShareCode(OrderInfo orderInfo) {
        new PermissionHelper().checkPermissions((FragmentActivity) getContext(), new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {

                if (!TextUtils.isEmpty(orderInfo.billno)) {
                    String base64BillNo = Base64Utils.encode(orderInfo.billno);
                    Bitmap bitmap = createQRCodeWithLogo(base64BillNo, ImageUtils.getBitmap(R.mipmap.icon_app));
                    new QRCodeDialog(getContext(), bitmap).show();
                } else {
                    showToast("获取订单信息失败");
                }

            }

            @Override
            public void shouldShowRequestPermissionRationale() {

            }

            @Override
            public void grantedForbidResult() {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 生成简单的带logo的二维码
     *
     * @param content
     * @param logo
     */
    @IOThread(ThreadType.Single)
    private Bitmap createQRCodeWithLogo(String content, Bitmap logo) {
        Bitmap bitmap = XQRCode.createQRCodeWithLogo(content, 400, 400, logo);
        return bitmap;
    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        if (mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.page = page;
            orderCondition.searchKey = mSearchKey;
            getPresenter().requestOrderList(mIOrderStatus.getOrderListObservable(orderCondition), isDialog);
        }
    }

    @Override
    public void initData() {

        if (mIOrderStatus != null) {
            setSearchKeyHint(mIOrderStatus.getSearchHint());
        }



    }

    @Override
    protected void requestSearch(String searchKey) {
        mSearchKey = searchKey;
        refreshData(true);
    }

    @Override
    protected void changeSearchKey(String searchKey) {
        mSearchKey = searchKey;
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_ORDER_LIST:
                if (isHasLoadData())
                    refreshData(false);
                break;
        }
    }



    private void showTerminateDialog(OrderInfo orderInfo) {
        new OperateTipDialog.Builder(getActivity())
                .title("原来的价格为："+orderInfo.tradprice+"元")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入要修改的价格");
                            return;
                        }
                        dialog.dismiss();

                        changeYunShuPrice(orderInfo.dispatchno,reason);
                    }
                })
                .show();
    }

    private void changeYunShuPrice(String dispatchno,String price) {

        Map<String, String> map = new HashMap<>();
        map.put("billno", dispatchno);
        map.put("price", price);
        new CommonModel().subscribe(getActivity(), CommonConfig.getInstance().create(OrderApiService.class).changePriceYunShu(map), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {

//                    EventBusManage.operateActivityFinish();
//                    EventBusManage.refreshOrderDetail();
                    EventBusManage.refreshOrderList();
                    ToastUtil.showShortToast("调整成功");

                } else {
                    ToastUtil.showShortToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                ToastUtil.showShortToast(e.message);
            }
        });
    }



    private void showWeightDialog(OrderInfo orderInfo) {
        new OperateTipDialog.Builder(getActivity())
                .title("原来的重量为："+orderInfo.tradweight+"元")
                .input(new OperateTipDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull OperateTipDialog dialog, CharSequence input) {
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new OperateTipDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull OperateTipDialog dialog) {
                        String reason = dialog.getInputContent();
                        if (TextUtils.isEmpty(reason)) {
                            ToastUtil.showShortToast("请输入要修改的重量");
                            return;
                        }
                        dialog.dismiss();

                        changeYunShuWeight(orderInfo.dispatchno,reason);
                    }
                })
                .show();
    }

    private void changeYunShuWeight(String dispatchno,String weight) {

        Map<String, String> map = new HashMap<>();
        map.put("billno", dispatchno);
        map.put("weight", weight);
        new CommonModel().subscribe(getActivity(), CommonConfig.getInstance().create(OrderApiService.class).changePriceYunShu(map), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {

//                    EventBusManage.operateActivityFinish();
//                    EventBusManage.refreshOrderDetail();
                    EventBusManage.refreshOrderList();
                    ToastUtil.showShortToast("调整成功");

                } else {
                    ToastUtil.showShortToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                ToastUtil.showShortToast(e.message);
            }
        });
    }



    private void yunfeiJIsuan(OrderInfo mOrderInfo) {
        if (mOrderInfo != null && mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.dispatchNo = mOrderInfo.dispatchno;
            orderCondition.billNo = mOrderInfo.billno;
            orderCondition.orderId = mOrderInfo.id;
            requestOrderDetail(mIOrderStatus.getOrderDetailObservable(orderCondition), true, mIOrderStatus.getOrderStatusType());
        }
    }


    public void requestOrderDetail(Observable observable, boolean isDialog, int orderType) {
        OrderModel mModel = new OrderModel();
        mModel.orderDetailModel(getActivity(), observable, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<OrderInfo>>() {
            @Override
            public void onNext(CommonResponse<OrderInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    OrderInfo info = commonResponse.getData();
                    if (null != info && mIOrderStatus != null) {
//                            getView().showOrderDetailList(mIOrderStatus.getOrderDetailList(info));

                        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
                        if (2 == rolePosition) {
                            //2 销售，3物流
                            Intent intent = new Intent(getActivity(), SaleCarFreightActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO,info);
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
                        } else {
                            OrderOperateInfo  orderOperateInfo = new OrderOperateInfo();
                            orderOperateInfo.operate = "运费计算";
                            orderOperateInfo.iOrderOperate = new FreightOperate();
                            orderOperateInfo.orderInfo = info;
                            orderOperateInfo.type=0;
                            orderOperateInfo.isEnable=true;
                            IOrderOperate iOrderOperate = orderOperateInfo.iOrderOperate;
                            iOrderOperate.orderOperate(getActivity(), orderOperateInfo);
                        }

                    }
                } else {
                    setMsg(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });



    }



    private void yunfeiJIsuanLook(OrderInfo mOrderInfo) {
        if (mOrderInfo != null && mIOrderStatus != null) {
            OrderCondition orderCondition = new OrderCondition();
            orderCondition.dispatchNo = mOrderInfo.dispatchno;
            orderCondition.billNo = mOrderInfo.billno;
            orderCondition.orderId = mOrderInfo.id;
            requestOrderDetailLook(mIOrderStatus.getOrderDetailObservable(orderCondition), true, mIOrderStatus.getOrderStatusType());
        }
    }


    public void requestOrderDetailLook(Observable observable, boolean isDialog, int orderType) {
        OrderModel mModel = new OrderModel();
        mModel.orderDetailModel(getActivity(), observable, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<OrderInfo>>() {
            @Override
            public void onNext(CommonResponse<OrderInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                        OrderInfo info = commonResponse.getData();
                        if (null != info && mIOrderStatus != null) {
//                            getView().showOrderDetailList(mIOrderStatus.getOrderDetailList(info));

//                        int rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
//                        if (2 == rolePosition) {
                            //2 销售，3物流
                            Intent intent = new Intent(getActivity(), SaleCarFreightLookActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(KeyValue.KEY_ORDER_INFO, info);
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
//                        } else {
//                            OrderOperateInfo  orderOperateInfo = new OrderOperateInfo();
//                            orderOperateInfo.operate = "运费计算";
//                            orderOperateInfo.iOrderOperate = new FreightOperate();
//                            orderOperateInfo.orderInfo = info;
//                            orderOperateInfo.type=0;
//                            orderOperateInfo.isEnable=true;
//                            IOrderOperate iOrderOperate = orderOperateInfo.iOrderOperate;
//                            iOrderOperate.orderOperate(getActivity(), orderOperateInfo);
//                        }

                        }

                } else {
                    setMsg(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                setMsg(e.message);
            }
        });



    }










}
